using Finbuckle.MultiTenant;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
using MultiTenant.SeparateSchema.Api;
using MultiTenant.SeparateSchema.Api.Data;
using MultiTenant.SeparateSchema.Api.Data.Context;
using MultiTenant.SeparateSchema.Api.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthorization();
builder.Services.AddAuthentication();

// 迁移TenantInfo到public schema,IMultiTenantStore会使用到它
builder.Services.AddDbContext<TenantInfoStoreDbContext>(
	options => options.UseNpgsql("Host=localhost; Port=5432; Database=tenant_db;Username=root;Password=123456"));

// 迁移租户数据到租户schema
builder.Services.AddDbContext<MigrationDbContext>(
	options => options
		.UseNpgsql("Host=localhost; Port=5432; Database=tenant_db;Username=root;Password=123456", npgsqlOptions =>
			npgsqlOptions.MigrationsHistoryTable(HistoryRepository.DefaultTableName, Schemas.TenantA)));

builder.Services.AddMultiTenant<AppTenantInfo>()
	.WithHeaderStrategy("X-Tenant")
	.WithEFCoreStore<TenantInfoStoreDbContext, AppTenantInfo>();

builder.Services.AddDbContext<ApplicationDbContext>(
	options => options.UseNpgsql("Host=localhost; Port=5432; Database=tenant_db;Username=root;Password=123456"));

var app = builder.Build();
app.MapGet("/", (HttpContext httpContext) =>
{
	var tenantInfo = httpContext.GetMultiTenantContext<AppTenantInfo>().TenantInfo;
	if (tenantInfo is null)
	{
		return Results.BadRequest();
	}
	return Results.Ok(new
	{
		tenantInfo.Identifier,
		tenantInfo.Id
	});
});
app.MapGet("/api/products", async (ApplicationDbContext context) 
	=> Results.Ok(await context.Products.ToListAsync()));
await app.ApplyMigrateAsync();
app.UseHttpsRedirection();
app.UseRouting();
app.UseMultiTenant();
app.UseAuthentication();
app.UseAuthorization();
app.Run();

